const express = require("express");
const Classify = require("../data/models/Classify");
const Document = require("../data/models/Document");
const User = require("../data/models/User");
const Config = require("../data/models/Config");
const router = express.Router();
const Search = require("../controller/Search");

module.exports = router;

const check = (req, res, next) => {
  try {
    let name = req.headers.user;
    User.findOne({ name }, (err, doc) => {
      if (err) res.status(500).send(err);
      if (doc) {
        req.user = doc._id;
        next();
      } else res.send({ Code: 401, Msg: "没有选定用户" });
    });
  } catch (error) {
    res.send({ Code: 401, Msg: "token失效" });
  }
};

router.get("/Classify", check, (req, res) => {
  // 获取分类列表
  Classify.findOne({ name: req.query.name, user: req.user }).then(data => {
    res.send(data.tag);
  });
});

router.get("/NewsList", check, (req, res) => {
  // 获取文档列表
  Search.Get(Document, { "tag._id": req.query.tag, user: req.user }, req, res);
});

router.get("/getSingleDoc", check, (req, res) => {
  // 获取单个文档
  Document.findById(req.query.id, (err, doc) => {
    res.send(doc);
  });
});

router.get("/config", check, (req, res) => {
  // 获取底部
  Config.findOne({ user: req.user }, (err, doc) => {
    if (err) res.status(500).send(err);
    res.send(doc);
  });
});

router.get("/GameInfoNews", check, (req, res) => {
  // 获取新手资料的数据
  Document.find({ "tag._id": req.query.tag, user: req.user }, (err, doc) => {
    res.send(doc);
  });
});

router.get("/HomeDoc", check, async (req, res) => {
  const first = await Document.find({ user: req.user }).limit(7).sort({ createdAt: -1 });
  const second = await Document.find({ user: req.user, "classify.name": "news" }).limit(7).sort({ createdAt: -1 });
  const third = await Document.find({ user: req.user, "classify.name": "activity" }).limit(7).sort({ createdAt: -1 });
  const fourth = await Document.find({ user: req.user, "classify.name": "topic" }).limit(7).sort({ createdAt: -1 });

  res.send([
    { title: "最新", isHot: first[0], List: first.slice(1) },
    { title: "新闻", isHot: second[0], List: second.slice(1) },
    { title: "活动", isHot: third[0], List: third.slice(1) },
    { title: "专题", isHot: fourth[0], List: fourth.slice(1) },
  ]);
});

router.get("/HomeBanner", check, (req, res) => {
  Document.find({ user: req.user, "classify.name": "banner" })
    .limit(4)
    .exec((err, doc) => {
      res.send(doc);
    });
});
